package com.ddwl.common.config;

import brave.Tracer;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ddwl.common.exception.CommonException;
import com.ddwl.common.feign.thirdparty.DingTalkApi;
import com.ddwl.schema.bo.gate.DingTalkBo;
import com.ddwl.schema.vo.gate.DingTalkRestVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import java.text.MessageFormat;

@RefreshScope
@Slf4j
@Configuration
@RequiredArgsConstructor
public class DingTalkNotify {

    @Value("${dingtalk.exception_robot.access_token}")
    private String accessToken;
    @Value("${spring.application.name}")
    private String appName;
    @Value("${spring.profiles.active}")
    private String profileActive;

    private final DingTalkApi dingTalkApi;
    private final Tracer tracer;

    @Async
    public void exceptionNotify(Throwable e){
        StringBuilder stackTrace = new StringBuilder(e.getClass().getName() + ": " + e.getMessage() + "\n");
        int i = 1, len = 8;
        if (e instanceof CommonException) {
            len = 2;
        }
        for (StackTraceElement ele : e.getStackTrace()) {
            if (i >= len) {
                break;
            }
            stackTrace.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n",
                    ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));
            i++;
        }
        exceptionNotify(appName,stackTrace.toString(),tracer.currentSpan().context().traceIdString(),profileActive);
    }

    public void exceptionNotify(String appName,String stack,String traceId, String profileActive) {
        DingTalkBo msg = new DingTalkBo();
        DingTalkBo.Text text = msg.new Text();
        StringBuilder content = new StringBuilder().append("## ").append(appName).append("服务异常[火][敲打][广播]\n ---\n");
        content.append("- traceId:").append(traceId).append("\n");
        content.append("- 环境:").append(profileActive).append("\n");
        content.append("- 堆栈信息:").append(stack).append("\n");
        if("prod".equals(profileActive)) {
            content.append("- [查看全部日志](http://106.53.222.65:32160/app/kibana#/discover?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:now-15m,to:now))&_a=(columns:!(APP_NAME,level,message),filters:!(),interval:auto,query:(language:kuery,query:'traceId:").append(traceId).append("'),sort:!()))").append("\n");
        }
        content.append("- ").append(DateUtil.formatDateTime(DateUtil.date()));
        text.setText(content.toString());
        msg.setMsgtype("markdown");
        text.setTitle(" ❌ 服务异常");
        msg.setMarkdown(text);
        DingTalkBo.At at = msg.new At();
        at.setAtAll(true);
        msg.setAt(at);
        log.info("dingding exception msg: {}", JSON.toJSONString(msg));
        try{
            DingTalkRestVo resp = dingTalkApi.send(accessToken, msg);
            log.info("dingding exception resp: {}", resp);
        } catch (Exception e){
            log.error("钉钉消息推送日常",e);
        }
    }
}

